<template>
  <div class="employees-container">
    <div class="app-container">
      <PageTools>
        <template #left>
          <span>总记录数: {{ total }}条</span>
        </template>

        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import?type=user')">excel导入</el-button>
          <el-button type="danger" size="small" @click="handleExport">excel导出</el-button>
          <el-button type="primary" size="small" @click="isShow = true">新增员工</el-button>
        </template>
      </PageTools>

      <el-card v-loading="loading" style="margin-top: 10px;">
        <el-table :data="list" border>
          <el-table-column label="序号" type="index" :index="indexMethod" sortable="" width="100" />
          <el-table-column label="头像" prop="staffPhoto" sortable="">
            <template #default="{ row }">
              <img
                v-imgerror="errorImg"
                class="staffPhoto"
                :src="row.staffPhoto || defaultPhoto"
                alt=""
                @click="handleImgClick ( row.staffPhoto )"
              >

            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="手机号" prop="mobile" sortable="" />
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column :formatter="formatEmploy" label="聘用形式" prop="formOfEmployment" sortable="" />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" sortable="">
            <template #default="{ row }">
              {{ row.timeOfEntry | formatTime('YYYY年MM月DD日') }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="handleRoleAssign(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="del(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :current-page="page"
            :page-sizes="[1,2,3,4,5,6,7,8,9,10]"
            :page-size="pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          >
            />
          </el-pagination></div>
      </el-card>
      <!-- 显示头像弹框 -->
      <el-dialog
        title="二维码预览图片"
        width="400px"
        :visible="showImg"
        @close="showImg = false"
      >
        <div style="text-align: center">
          <canvas ref="myCanvas" />
        </div>
      </el-dialog>
      <AddEmployee :show-dialog.sync="isShow" @add-employee="getUserList" />

      <AssignRole :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import { reqDelEmployee, reqGetUserList } from '@/api/employees'
import AddEmployee from '@/views/employees/components/AddEmployee.vue'
import obj from '@/constant/employees'
import dayjs from 'dayjs'
import errorImg from '@/assets/common/bigUserHeader.png'
import QrCode from 'qrcode'
import AssignRole from './components/AssignRole.vue'
// import { Loading } from 'element-ui'
export default {
  name: 'Employees',
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      page: 1,
      pagesize: 5,
      list: [],
      total: 0,
      loading: false,
      isShow: false,
      defaultPhoto: 'https://dss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2146034403,1504718527&fm=26&gp=0.jpg',
      errorImg,
      showImg: false,
      showRoleDialog: false,
      userId: '' // 用户存储角色点击了那个用户的ID
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 获取最新数据 ，渲染
    async getUserList() {
      this.loading = true
      const { data: { rows, total }} = await reqGetUserList(this.page, this.pagesize)
      // console.log({ data: { rows, total }})
      this.list = rows
      this.total = total
      this.loading = false
    },
    handleCurrentChange(val) {
      //  val 当前页码
      this.page = val
      // 把他的页码更新到自己的page里
      // 发请求 就拿到更新页码 重新的请求 就会重新渲染
      this.getUserList()
    },
    handleSizeChange(val) {
      // val 他是每页条数 这个是用户自己选的每页条数
      this.pagesize = val
      // 回道第一页
      this.page = 1
      // 获取数据
      this.getUserList()
    },
    indexMethod(index) {
      // index 就是从下标0开始
      return index + 1 + this.pagesize * (this.page - 1)
      // 前面一个有多少页 * 每页多少数据 +前面总数
    },
    formatEmploy(row, column, cellValue, index) {
      // return cellValue === 1 ? '正式工' : '临时工'
      const arr = obj.hireType
      const res = arr.find(item => item.id === +cellValue)
      return res ? res.value : '未知'
    },
    del(id) {
      // 让用户确认
      this.$confirm('该操作将永久删除改员工').then(async() => {
        // 发送请求
        const res = await reqDelEmployee(id)
        console.log(res)
        // 提示用户
        this.$message.success('删除员工成功')
        // 最后一个数据 且页码大于1
        if (this.list.length === 1 && this.page > 1) {
          // 回到上一页
          this.page--
        }
        // 获取新数据
        this.getUserList()
      }).catch(() => {
        console.log('取消')
      })
    },
    async handleExport() {
      // 表头
      const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      // 中英文对照表
      const headersRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 原数据
      const { data: { rows }} = await reqGetUserList(1, this.total)
      console.log(rows)

      // 多表头
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
      // 合并单元格
      const merges = ['A1:A2', 'B1:F1', 'G1:G2']

      const result = this.transOriginTo2Wei(rows, headersArr, headersRelations)

      import('@/vendor/Export2Excel').then(excel => {
        console.log(excel)
        excel.export_json_to_excel({
          // 表格的表头
          header: headersArr,
          // 表格的主体数据(固定格式->二维数组)
          data: result,
          filename: '员工信息表',
          autoWidth: true, // 宽度自适应 非必填
          bookType: 'xlsx', // 文件格式 非必填
          multiHeader,
          merges
        })
      })
    },
    transOriginTo2Wei(rows, headersArr, headersRelations) {
      const arr = []
      rows.forEach(item => {
        const res = []

        headersArr.forEach(v => {
          const englishKey = headersRelations[v]
          let val = item[englishKey]
          if (englishKey === 'formOfEmployment') {
            const { hireType } = obj
            const resObj = hireType.find(v => v.id === +val)
            val = resObj ? resObj.value : '未知'
          }
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            val = dayjs(val).format('YYYY年MM月DD日')
          }
          res.push(val)
        })
        arr.push(res)
      })
      return arr
    },
    handleImgClick(imgUrl) {
      console.log(imgUrl)
      if (!imgUrl) return
      // 异步dom更新的！！
      this.showImg = true

      this.$nextTick(() => {
        QrCode.toCanvas(this.$refs.myCanvas, imgUrl)
      })
    },
    handleRoleAssign(id) {
      this.showRoleDialog = true
      this.userId = id
    }
  }
}
</script>

<style lang="scss" scoped>
.employees-container {
  .staffPhoto {
    width: 70px;
    height: 70px;
    border-radius: 50%;
  }
}
</style>
